import {Injectable} from '@angular/core';
import {Service} from "./service";
import {finalize, Observable, tap} from "rxjs";
import {ComponentStore} from "@ngrx/component-store";

export interface User {
  id: number;
  name: string;
  email: string;
}

@Injectable({
  providedIn: 'root'
})
export class UserStore extends ComponentStore<{
  loading: boolean;
  users: User[];
}> {

  constructor(private service: Service) {
    super({loading: false, users: []});
  }

  // 定义改变 state 的方法
  readonly setLoading = this.updater((state, loading: boolean) => ({
    ...state,
    loading,
  }));

  readonly setUsers = this.updater((state, users: User[]) => {
    return {
      ...state,
      users,
    }
  });

  readonly fetchUsers = () => this.effect(() => {
    // 开始获取用户数据
    this.setLoading(true);
    // 发送请求并更新 state
    return this.service.getUsers().pipe(
      tap((data) => {
        this.setUsers(data.users)
      }),
      finalize(() => this.setLoading(false))
    );
  });

  // 定义一个取回loading state 值的 observable 的 helper 方法
  readonly loading$: Observable<boolean> = this.select(({loading}) => loading);

  // 定义一个取回users state 值的 observable 的 helper 方法
  readonly users$: Observable<User[]> = this.select(({users}) => users);
}
